#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @Time    : 2018/1/24 15:17
# @Author  : RNone
import datetime
import logging
import sys
import time
from pprint import pformat
import xlrd
from public import excel_control


def logging_config():
	# 配置Logging
	logging.getLogger('requests').setLevel(logging.WARNING)
	logging.getLogger('urllib3').setLevel(logging.WARNING)
	logging.getLogger('dicttoxml').setLevel(logging.WARNING)
	logging.basicConfig(level=logging.DEBUG,
						format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
						datefmt='%a, %d %b %Y %H:%M:%S',
						filename='.\\log\\%s.log' % (datetime.datetime.now().strftime('%Y-%m-%d')),
						filemode='a')
	console = logging.StreamHandler()
	console.setLevel(logging.INFO)
	formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
	console.setFormatter(formatter)
	logging.getLogger('').addHandler(console)


def main():
	'''读取用例配置'''
	ec = excel_control.excel_control()  # 实例化xls操作类
	confKeys = []  # 初始化用例标题列表
	casesSheet = ec.excel_read('.\\test_cases.xls')  # 读取xls文件
	wb = ec.readbook_to_writebook('.\\test_cases.xls')	#读取xls文件并转化为写入模式
	for row in range(0, casesSheet.nrows):  # 循环遍历每一行数据
		caseList = casesSheet.row_values(row)  # 将每一行数据取出
		if row < 10:
			if row == 3:
				host = caseList[0]
		elif row == 10:  # 将首行变量名取出
			confKeys = caseList  # 赋值给用例标题列表
		else:
			caseDict = ec.case_to_dict_from_cases(confKeys, caseList)  # 将用例参数取出，并用变量名匹配
			caseDict['host'] = host
			__import__('api.' + caseDict['module'])  # 动态导入需要的模块
			moudle = sys.modules['api.' + caseDict['module']]  # 实例化模块
			c = getattr(moudle, caseDict['module'])  # 根据参数导入需要的类
			obj = c()  # 实例化类
			func = getattr(obj, caseDict['function'])  # 根据参数导入需要的方法
			startTime = time.time()
			caseDict = func(caseDict)  # 执行方法，并将参数传入
			endTime = time.time()
			timeConsuming = endTime - startTime
			caseDict['timeConsuming'] = round(timeConsuming, 3)  # 单条用例耗时计算，取小数点后3位

			#格式化用例结果信息
			data = '[%s] : %s、%s %s 耗时为：%s秒' % (
				datetime.datetime.now(),
				caseDict['id'],
				caseDict['title'],
				caseDict['result'],
				caseDict['timeConsuming'])
			logging.info(data)  # 打印日志
			ec.result_output(caseDict)  # 输出结果至result文件
			#获取xml文件名
			filename = ec.xml_output(caseDict)
			#将结果写入xls文件
			wb = ec.excel_write(
				wb,
				row,
				confKeys.index('result'),
				caseDict['result'])
			#将xml文件链接写入xls文件
			wb = ec.excel_write_link(wb,
								 row,
								 confKeys.index('file'),
								 filename)
			# 将返回数据以字典形式格式化输出至日志
			# print(pprint.pprint(caseDict['response']))

			for i in pformat(caseDict['response']).splitlines():
				logging.debug(i.rstrip())

			# print('\n')
	try:
		wb.save('.\\test_cases.xls')
	except Exception as e:
		logging.error(e)
		wb.save('./result.xls')


if __name__ == '__main__':
	logging_config()
	main()
